<template>
    <div class="entrance">
        <van-nav-bar class="navBar" title="手动入场" left-text="返回" left-arrow @click-left="onClickLeft" />
        <el-form ref="form" :model="form"  size="mini" class="elForm" v-loading="loadingForm">
            <div class="carNum">
                <plateNumber :carNum="form.carNum" @getPlateLicense="getPlateLicense" :clickOutside=true></plateNumber>
            </div>
            <div class="uploadWrap">
                <el-upload
                    class="avatar-uploader"
                    :action="domain"
                    :data="QiniuData"
                    accept="image/*"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                    :on-change="handleChange"
                    :on-preview="handlePictureCardPreview"
                    :on-success="uploadSuccess"
                    :on-error="uploadError"
                    > <!-- :auto-upload="false" -->
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </div>
            <el-form-item label="入场时间：" label-width="83px">
                <!-- <el-input v-model="form.inTime"></el-input> -->
                <el-date-picker
                    class="fullWidth"
                    v-model="form.inTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择入场时间">
                </el-date-picker> 
            </el-form-item>
            <el-form-item class="footer">
                <!-- <el-button type="primary" @click="onSubmit">确认</el-button> -->
                <el-button type="primary" @click="changeAsyncOK">确认</el-button>
                <el-button @click="cancleHandle">取消</el-button>
            </el-form-item>
        </el-form>
        <!-- 手动入场弹窗 -->
        <el-dialog class="dialog"
            :visible.sync="confirmdialog"
            width="90%">
            <div class="content">
                <h3>{{form.carNum||form.imgCarNum}}</h3>
                <p>入场时间：{{form.inTime}}</p>
            </div>
            <span slot="footer" class="dialog-footer" center>
                <el-button type="primary" @click="changeAsyncOK('form')" size="mini">确 定</el-button>
            </span>
        </el-dialog>
    </div>    
</template>

<script>
import { mapGetters } from "vuex"
import { ImagePreview} from 'vant';
import ClickOutside from 'element-ui/src/utils/clickoutside'
import plateNumber from '@/components/plateNumber'
import { timeFormate } from '@/utils'
import * as imageConversion from 'image-conversion';
import axios from "axios";
export default {
    components: {
        [ImagePreview.Component.name]: ImagePreview.Component,
        plateNumber
    },
    data() {
        return {
            loadingForm:false,
            imgQuality: 0.8,
            confirmdialog:false,
            imageUrl:"",
            photoFile:'',
            form:{
                depId:'',
                imgCarNum:'',
                carNum:'',
                inTime:'',
                serialNum:"",
                parkId:'',
                imgId:''
            },
            QiniuData: {
                key: "", //图片名字处理
                token: "" //七牛云token
            },
            domain: "https://upload-z2.qiniup.com", // 七牛云的上传地址（华南区）
        }
    },
    computed: {
        ...mapGetters(["orgCategory",'carParkInfo'])
    },
    created() {
        this.form.depId = this.carParkInfo.depId||sessionStorage.getItem('depId')
        this.form.parkId = this.carParkInfo.id||JSON.parse(sessionStorage.getItem('carParkInfo')).id
        this.form.inTime = timeFormate(new Date())
        this.getQnToken();
    },
    methods: {
        onClickLeft(){
            this.$router.push('/deviceManage')
        },
        getPlateLicense(data){
            this.form.carNum = data
        },
        getQnToken(){
            this.$api.home.getQnToken().then(res=>{
                if(res.code == 200){                    
                    //debugger
                    this.QiniuData.token = res.message
                }else{
                    this.$toast(res.message);
                }
            }).catch((res) => {

            });
        },
        beforeUpload(param) {   
            this.loadingForm = true
            this.QiniuData.key = `upload_pic_${param.name}`;  
            const imgSize = param.size / 1024 / 1024;
            //console.log(imgSize);
            //这里做图片的压缩 如果大于1M我们进行等比压缩处理
            if (imgSize > 1) {
                const _this = this
                return new Promise(resolve => {
                    const reader = new FileReader()
                    const image = new Image()
                    //debugger
                    image.onload = (imageEvent) => {
                        const canvas = document.createElement('canvas');
                        const context = canvas.getContext('2d');
                        const width = image.width * _this.imgQuality
                        const height = image.height * _this.imgQuality
                        canvas.width = width;
                        canvas.height = height;
                        context.clearRect(0, 0, width, height);
                        context.drawImage(image, 0, 0, width, height);
                        const dataUrl = canvas.toDataURL(param.type);
                        const blobData = _this.dataURItoBlob(dataUrl, param.type);
                        
                        
                        resolve(blobData)
                    }
                    reader.onload = (e => {
                        image.src = e.target.result;
                    });
                    reader.readAsDataURL(param);
                })
            }
        },
        dataURItoBlob(dataURI, type) {
            //console.log(dataURI, type);
            var binary = atob(dataURI.split(',')[1]);
            var array = [];
            for (var i = 0; i < binary.length; i++) {
                array.push(binary.charCodeAt(i));
            }
            return new Blob([new Uint8Array(array)], {
                type: type
            });
        },
        getCarNum(image){
            axios.post('http://ocrcp.market.alicloudapi.com/rest/160601/ocr/ocr_vehicle_plate.json', {
                image: image,
                configure: "{\"multi_crop\":false}"
            },{
                headers: {
                    'content-type': 'application/json',
                    "Authorization":'APPCODE c37518be3ff64fb4a68ede48220aa785'  //token换成从缓存获取
                }
            }).then((res) =>{
                this.loadingForm = false
                if(res.data.request_id){
                    this.form.imgCarNum = res.data.plates[0].txt
                    this.form.carNum = ""
                }
            }).catch((error)=> {
                //this.imageUrl = ""
                this.loadingForm = false
                this.$toast('上传识别车牌失败，请重新上传')
                console.log(error);
            });

        },
        transformBase64(file){
            return new Promise(((resolve, reject) => {
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function(e){ 
                    resolve(e.target.result.split(',')[1])
                }
            }))
        },
        handleChange(file, fileList){
            //debugger
            let fileObj = file.raw
            this.imageUrl = URL.createObjectURL(fileObj);
            this.photoFile = fileObj
            this.transformBase64(file.raw).then(data=>{
                this.getCarNum(data)
            })
        },
        uploadSuccess(response, file, fileList){
            //debugger
            this.form.imgId = response.name
        },
        uploadError(err, file, fileList){
            this.$toast('上传图片失败')
        },
        onSubmit(){
            Toast.loading({
                duration: 0, // 持续展示 toast
                forbidClick: true,
                message: '倒计时 3 秒',
            })
            if(this.form.carNum == ''&&this.form.imgCarNum==""){
                this.$toast('请输入车牌号')
                return
            }else if(this.form.carNum != ''&&this.form.carNum.length < 7){
                this.$toast('请输入正确的车牌号')
                return
            }/* else if(this.form.imgId == ""){
                this.$toast('请上传图片')
                return
            } */else if(!this.form.inTime){
                this.$toast("请选择入场时间");
                return
            }
            this.confirmdialog = true
        },
        changeAsyncOK(){
            if(this.form.carNum == ''&&this.form.imgCarNum==""){
                this.$toast('请输入车牌号')
                return
            }else if(this.form.carNum != ''&&this.form.carNum.length < 7){
                this.$toast('请输入正确的车牌号')
                return
            }/* else if(this.form.imgId == ""){
                this.$toast('请上传图片')
                return
            } */else if(!this.form.inTime){
                this.$toast("请选择入场时间");
                return
            }
            let param = {}
            if(this.form.carNum!=''){
                param = {
                    depId:this.form.depId,
                    carNum:this.form.carNum,
                    inTime:this.form.inTime,
                    serialNum:this.form.serialNum,
                    parkId:this.form.parkId,
                    imgId:''
                }
            }else{
                param = {
                    depId:this.form.depId,
                    carNum:this.form.imgCarNum,
                    inTime:this.form.inTime,
                    serialNum:this.form.serialNum,
                    parkId:this.form.parkId,
                    imgId:this.form.imgId
                }
            }
            this.$api.home.addPresentCar(param).then(res=>{
                if(res.code == 200){
                    this.confirmdialog = false                    
                    this.$toast(param.carNum+'在'+param.inTime+'入场成功')
                    this.form.carNum = ""
                    this.form.imgCarNum = ""
                    this.imageUrl = ""
                }else{
                    this.$toast(res.message);
                }
            }).catch((res) => {
                this.loading = false;
            });
        },
        cancleHandle(){
            this.onClickLeft()
        }
    },
}
</script>

<style  lang="less" scoped>
    .entrance {
        .elForm{
            padding: .3rem .2rem;
            background-color: #fff;
            .footer{
                text-align: center;
            }
        }
        .carNum{
            width: 100%;
            margin-bottom: 10px;
            /deep/ .wrap{
                padding: 0;
                border-bottom:0;
                .singleBlock{
                    display: inline-block;
                    width: 100%;
                }
                .card-header{
                    float: left;
                    display: inline-block;
                    width: 70px;
                    padding-right:12px;
                    margin:0;
                }
                .num-box{
                    display: inline-flex;
                    width: calc(100% - 70px);
                }
            }
        }
        .avatar-uploader {
            /deep/ .el-upload {
                width: 100%;
                height:4rem;
                line-height: 4rem;
                border: 1px dashed #d9d9d9;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
            }
            .el-upload:hover {
                border-color: #409EFF;
            }            
            .avatar-uploader-icon {
                font-size: 28px;
                color: #8c939d;
                width: 100%;
                height: 3rem;
                line-height: 3rem;
                text-align: center;
            }
            .avatar {
                max-width: 100%;
                margin: auto;
                vertical-align: middle;
            }
        }
        /deep/ .dialog{
            .el-dialog__header{
                background-color: #409EFF;
            }
            .el-dialog__headerbtn{
                top:7px;
                .el-dialog__close {
                    color: #fff;
                }
            }
            .content{
                text-align: center;
            }
            .dialog-footer{
                display: inline-block;
                width: 100%;
                text-align: center;
            }
        }
    }
</style>